<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible" center>
    <el-button class="miui-dialog-close-btn" @click="visible = false">关闭页面</el-button>
    <el-form :model="dataForm" :rules="dataRule" class="verify-form" ref="dataForm" label-width="80px">
      <el-form-item label="折扣卡卡号" prop="code" v-if="type != 'batchAdd'">
        <el-input v-model="dataForm.code" placeholder="折扣编码"></el-input>
      </el-form-item>
      <el-form-item label="折扣卡卡号前段" prop="codeBefore" v-if="type == 'batchAdd'">
        <el-input v-model="dataForm.codeBefore" placeholder="折扣编码"></el-input>
      </el-form-item>
      <el-form-item label="折扣卡卡号后端" prop="codeAfter" v-if="type == 'batchAdd'">
        <el-input v-model="dataForm.codeAfter" placeholder="折扣编码"></el-input>
      </el-form-item>
      <el-form-item label="持卡人姓名" prop="possessorName">
        <el-input v-model="dataForm.possessorName" placeholder="持卡人姓名"></el-input>
      </el-form-item>
      <el-form-item label="身份证号" prop="idNumber">
        <el-input v-model="dataForm.idNumber" placeholder="身份证号"></el-input>
      </el-form-item>
      <el-form-item label="折扣率(0-1)" prop="rate">
        <el-input v-model="dataForm.rate" placeholder="折扣率(0-1)"></el-input>
      </el-form-item>
      <el-form-item label="是否设置密码" prop="isPassword">
        <el-checkbox v-model="dataForm.isPassword" true-label='1' false-label='0'>是否设置密码</el-checkbox>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="dataForm.password" placeholder="密码" v-if="dataForm.isPassword == 1"></el-input>
      </el-form-item>
      <el-form-item label="使用次数类型" prop="useType">
        <el-checkbox v-model="dataForm.useType" true-label="1" false-label="0">使用次数类型</el-checkbox>
      </el-form-item>
      <el-form-item label="使用次数" prop="useNumber">
        <el-input v-model="dataForm.useNumber" placeholder="使用次数" v-if="dataForm.useType ==1"></el-input>
      </el-form-item>
      <el-form-item label="是否设置有效期" prop="periodOfValidityType">
        <el-checkbox v-model="dataForm.periodOfValidityType" true-label="1" false-label="0">是否设置有效期</el-checkbox>
      </el-form-item>
      <el-form-item label="有效期开始" prop="periodOfValidityStart">
        <el-date-picker v-if="dataForm.periodOfValidityType == 1" v-model="dataForm.periodOfValidityStart" type="date"
          placeholder="选择日期" value-format="yyyy-MM-dd" @change="startDateChange" :picker-options="startDateLimit"></el-date-picker>
      </el-form-item>
      <el-form-item label="有效期结束" prop="periodOfValidityEnd">
        <el-date-picker v-if="dataForm.periodOfValidityType == 1" v-model="dataForm.periodOfValidityEnd" type="date"
          placeholder="选择日期" value-format="yyyy-MM-dd" :disabled="!dataForm.periodOfValidityStart" @focus="changeEnd"
          :picker-options="endDateLimit"></el-date-picker>
      </el-form-item>
      <el-form-item label="数量" prop="number" v-if="type == 'batchAdd'">
        <el-input v-model="dataForm.number" placeholder="数量"></el-input>
      </el-form-item>
      <el-form-item label="商品类别" prop="ctgIds">
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="dataForm.ctgIds" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="ctg in ctgOptions" :label="ctg.value" :key="ctg.value">{{ctg.label}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit" :loading="ischeck" v-prevent-re-click>确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import {
    getObj,
    addObj,
    putObj,
    batchAddObj
  } from "@/api/eims/eimsdiscountcard";
  import {
    getCtgList
  } from "@/api/eims/ctg";

  export default {
    data() {
      var valueCheck = (rule, value, callback) => {
        if (value > 1) {
          callback(new Error("请输入0-1之间含两位小数的值"));
        } else if (value < 0) {
          callback(new Error("请输入0-1之间含两位小数的值!"));
        } else {
          callback();
        }
      };
      var codeAfterCheck = (rule, value, callback) => {
        let numPattern = /^-?\d*\.?\d+$/
        if (!numPattern.test(value)) {
          callback(new Error("请输入长度在 3 到 6 个数字"));
        } else {
          callback()
        }
      };
      var codeBeforeCheck = (rule, value, callback) => {
        let numPattern = /^\w+$/
        if (!numPattern.test(value)) {
          callback(new Error("请输入长度在 1 到 6 位字符"));
        } else {
          callback()
        }
      };
      var codeCheck = (rule, value, callback) => {
        let numPattern = /^\w+$/
        if (!numPattern.test(value)) {
          callback(new Error("请输入字母或者数字,最长长度为12位"));
        } else {
          callback()
        }
      };
      return {
        ischeck: false,
        visible: false,
        type: '',
        dataForm: {
          id: 0,
          code: "",
          codeBefore: "",
          codeAfter: "",
          possessorName: "",
          idNumber: "",
          rate: "",
          isPassword: "",
          password: "",
          useType: "",
          useNumber: "",
          periodOfValidityType: "",
          periodOfValidityStart: "",
          periodOfValidityEnd: "",
          number: "",
          ctgIds: []
        },
        startDateLimit: {
          disabledDate: (time) => {
            return this.dealDisabledDate(time);
          }

        },
        endDateLimit: {
          disabledDate: (time) => {
            return this.dealDisabledDateEnd(time);
          }
        },
        isIndeterminate: false,
        checkAll: false,
        ctgOptions: [],
        dataRule: {
          code: [{
              required: true,
              message: "折扣卡卡号不能为空",
              trigger: "blur"
            },
            {
              min: 1,
              max: 12,
              message: '请输入长度在 1 到 12 位字符',
              trigger: 'blur'
            },
            {
              validator: codeCheck
            }
          ],
          codeBefore: [{
              required: true,
              message: "折扣卡卡号前段不能为空",
              trigger: "blur"
            },
            {
              min: 1,
              max: 6,
              message: '请输入长度在 1 到 6 位字符',
              trigger: 'blur'
            },
            {
              validator: codeBeforeCheck
            }
          ],
          codeAfter: [{
              required: true,
              message: "折扣卡卡号不能为空",
              trigger: 'blur'
            },
            {
              min: 3,
              max: 6,
              message: '长度在 3 到 6 个数字字符',
              trigger: 'blur'
            },
            {
              validator: codeAfterCheck
            }
          ],
          rate: [{
              required: true,
              message: "折扣率(0-1)不能为空",
              trigger: "blur"
            },
            {
              validator: valueCheck
            }
          ],
          ctgIds: [{
            required: true,
            message: "不能为空",
            trigger: "blur"
          }],
          number: [{
            required: true,
            message: "不能为空",
            trigger: "blur"
          }]
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      dealDisabledDate(time) {
        var times = Date.now()
        return time.getTime() < (times - 86400000);
      },
      dealDisabledDateEnd(time) {
        let startTime = new Date(this.dataForm.periodOfValidityStart).getTime()
        return time.getTime() < (startTime - 86400000)
      },

      init(data) {
        this.dataForm.id = data.id || 0;
        this.type = data.type
        this.visible = true;
        this.$nextTick(() => {
          this.$refs["dataForm"].resetFields();
          if (this.dataForm.id) {
            this.isIndeterminate = true;
            getObj(this.dataForm.id).then(response => {
              if(response.data.code == '0'){
                this.dataForm = response.data.data;
                this.dataForm.isPassword = (this.dataForm.isPassword) ? true : false
                this.dataForm.useType = (this.dataForm.useType) ? true : false
                this.dataForm.periodOfValidityType = (this.dataForm.periodOfValidityType) ? true : false
              }else{
                this.$message.error(response.data.msg)
              }
            });
          }
        });
      },
      // 表单提交
      dataFormSubmit() {
        this.ischeck = true
        this.$refs["dataForm"].validate(valid => {
          this.dataForm.isPassword = (this.dataForm.isPassword) ? 1 : 0
          this.dataForm.useType = (this.dataForm.useType) ? 1 : 0
          this.dataForm.periodOfValidityType = (this.dataForm.periodOfValidityType) ? 1 : 0
          if (valid) {
            if (this.dataForm.id) {
              putObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  this.$message.success("修改成功");
                  this.visible = false;
                  this.$emit("refreshDataList");
                }else{
                  this.$message.error(response.data.msg)
                }
                this.ischeck = false
              }).catch(() => {
                this.ischeck = false
              })
            } else {
              if (this.type == 'add') {
                addObj(this.dataForm).then(response => {
                  if(response.data.code == '0'){
                    this.$message.success("添加成功")
                    this.visible = false;
                    this.$emit("refreshDataList");
                  }else{
                    this.$message.error(response.data.msg)
                  }
                  this.ischeck = false
                }).catch(() => {
                  this.ischeck = false
                })
              } else {
                // 批量新增
                batchAddObj(this.dataForm).then(response => {
                  if(response.data.code == '0'){
                    this.$message.success("添加成功")
                    this.visible = false;
                    this.$emit("refreshDataList");
                  }else{
                    this.$message.error(response.data.msg)
                  }
                  this.ischeck = false
                }).catch(() => {
                  this.ischeck = false
                })
              }
            }
          }else{
						this.ischeck = false
					}
        });
      },
      getList() {
        getCtgList().then(response => {
          if(response.data.code == '0'){
            let result = response.data.data;
            let list = [];
            result.forEach(item => {
              list.push({
                value: item.id,
                label: item.name
              });
            });
            this.ctgOptions = list;
          }else{
            this.$message.error(response.data.msg)
          }
        });
      },
      handleCheckAllChange(val) {
        if (val) {
          this.ctgOptions.forEach(item => {
            this.dataForm.ctgIds.push(item.value);
          });
        } else {
          this.dataForm.ctgIds = [];
        }
        this.isIndeterminate = false;
      },
      handleCheckedCitiesChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.ctgOptions.length;
        this.isIndeterminate =
          checkedCount > 0 && checkedCount < this.ctgOptions.length;
      },
      startDateChange(val) {
        if (!val) {
          this.dataForm.periodOfValidityEnd = ''
        }
      },
      changeEnd() {

      }
    },
  };
</script>
